package org.hsieh.tr.explore.ui.actions;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.eclipse.jface.action.IAction;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IViewActionDelegate;
import org.eclipse.ui.IViewPart;
import org.eclipse.ui.PlatformUI;
import org.hsieh.tr.explore.db.ISqlCommand;
import org.hsieh.tr.explore.ui.TransactionEditor;

public class AddSqlsToEditorAction implements IViewActionDelegate {

    private List<ISqlCommand> commands;

    private TransactionEditor editor;

    public void init(IViewPart view) {

    }

    public void run(IAction action) {
	if (commands != null && !commands.isEmpty()) {
	    IEditorPart currentEditor = getCurrentEditor();
	    if (currentEditor != null
		    && currentEditor instanceof TransactionEditor) {
		editor = (TransactionEditor) currentEditor;
		editor.addSQLCommands(commands);
		editor.setFocus();
	    }
	}
    }

    public void selectionChanged(IAction action, ISelection selection) {
	IEditorPart editor = getCurrentEditor();
	if (editor == null) {
	    action.setEnabled(false);
	} else {
	    if (editor instanceof TransactionEditor) {
		action.setEnabled(true);
		this.editor = (TransactionEditor) editor;
	    }
	}
	IStructuredSelection ss = (IStructuredSelection) selection;
	commands = new ArrayList<ISqlCommand>();
	for (Iterator iter = ss.iterator(); iter.hasNext();) {
	    ISqlCommand command = (ISqlCommand) iter.next();
	    commands.add(command);
	}
    }

    private IEditorPart getCurrentEditor() {
	return PlatformUI.getWorkbench().getActiveWorkbenchWindow()
		.getActivePage().getActiveEditor();
    }

}
